<template>
  <div class="app">
    <header>当前城市-北京 <i>&times;</i></header>
    <Search :showResult.sync="showResult" :searchVal.sync="searchVal" />
    <ResultCity v-if="showResult" :resultCityList="resultCityList" />
    <AllCityList v-else :list="list" :originList="originList" />
  </div>
</template>

<script>
import Search from './components/searchView.vue' // 搜索框组件
import AllCityList from './components/allCityList.vue' // 所有城市列表组件
import ResultCity from './components/resultCity.vue' // 结果城市组件
import axios from 'axios' // 引入axios

export default {
  components: {
    Search,
    AllCityList,
    ResultCity
  },
  data () {
    return {
      showResult: false, // 是否展示结果组件
      originList: null, // 原始数组
      list: null, // 城市列表
      searchVal: '' // 搜索框的值
    }
  },
  methods: {
    // 获取城市列表
    async getCity () {
      const res = await axios.get('https://m.maizuo.com/gateway', {
        headers: {
          'x-client-info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"174057150511175504904193"}',
          'x-host': 'mall.film-ticket.city.list'
        },
        params: {
          k: 6037502
        }
      })
      // console.log(res.data.data.cities)
      this.originList = res.data.data.cities
      // console.log(this.originList)
      this.list = this.format(this.originList)
    },
    // 重新排列数据
    format (cities) {
      return cities.reduce(
        (res, city) => {
          const first = city.pinyin[0].toUpperCase() // 拿到每一项的拼音首字母大写后的结果
          const findType = res.find(v => v.type === first) // 在结果res中按照type查找
          if (findType) { // 如果找到了
            findType.children.push(city) // 在找到的那一项里面childre里面再加一项city
          } else { // 如果没有找到
            res.push({ // 给res数组添加一项行的
              type: first, // 拼音首字母
              children: [city] // 城市
            })
          }
          return res // 返回结果
        }, [])
        .sort((a, b) => a.type.localeCompare(b.type)) // 进行排序
    }
  },
  computed: {
    resultCityList () {
      if (!this.searchVal) return []
      return this.originList.filter(v => v.name.includes(this.searchVal) || v.pinyin.includes(this.searchVal))
    }
  },
  created () {
    this.getCity() // 创建之后调用接口拿数据
  }
}
</script>

<style lang="scss" scoped>
.app {
  font-size: 0.16rem;
  overflow: hidden;
  background: #f4f4f4;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;

  header {
    height: 0.44rem;
    border-bottom: 0.01rem solid #f8f8f8;
    background: #fff;
    line-height: 0.44rem;
    position: relative;
    text-align: center;

    i {
      font-size: 0.3rem;
      position: absolute;
      top: -0.03rem;
      left: 0.03rem;
      color: #797d82;
      font-weight: normal;
    }
  }
}
</style>
